package com.yuyu.qingmangmall.order.interceptor;

import com.yuyu.common.constant.AuthServerConstant;
import com.yuyu.common.vo.SocialMemberVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class OrderWebInterceptor implements HandlerInterceptor {

    public static ThreadLocal<SocialMemberVo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 不拦截 uri为 /order/order/info/** 的请求
        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        // /order/order/info/{orderSn}
        boolean match1 = antPathMatcher.match("/order/order/status/**", uri);
        // 支付宝[异步通知]，告诉我们支付成功的信息 /payed/notify
        boolean match2 = antPathMatcher.match("/payed/**", uri);
        if (match1|| match2){
            return true;
        }

        SocialMemberVo loginUser = (SocialMemberVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
        if (loginUser==null){
            // 未登录
            request.getSession().setAttribute("msg","请先登录");

            response.sendRedirect("http://auth.qingmangmall.com/login.html");
            return false;
        }else {
            // 登陆状态
            threadLocal.set(loginUser);
            return true;
        }
    }
}
